// pages/buycar.js
const app = getApp();
Page({
  data: {
    listData: [],
    page: {
      pageSize: 20,
      pageNo: 1,
      openid: null
    },
    buttons: [
        {
            type: 'primary',
            className: '',
            text: '确认支付',
            value: 1
        }
    ],
    show: false,
    ids: [],
    order: [],
    settleAmount: 0,
    showStatus: false,
    product: {}, //当前需要修改属性的对象
    options: [],
    selectAttrIndex: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.findPage();
  },
  onShow: function () {
    this.findPage();
    this.setBuycatNum();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
   * 返回首页
   */
  goIndexPage: function () {
    wx.switchTab({
      url: '../index/index',
    })
  },
  findPage: function() {
    wx.cloud.callFunction({
      // 需调用的云函数名
      name: 'buycarApi',
      // 传给云函数的参数
      data: {
        method: "findPageByUser",
        args: this.page
      },
      // 成功回调
      complete: (res)=>{
        console.log(res, "查询购物车人")
        this.setData({
          listData: res.result.rstData.data
        });
      }
    });
  },
  /**
   * 每个商品改变数量的输入框
   * @param {*} e 
   */
  numChange: function(e) {
    const index = e.currentTarget.dataset.index;
    this.data.listData[index].num =  e.detail.count;
    this.setData({
      listData: this.data.listData
    });
    console.log(e,index,"改变数量", e.detail.count);
  },
  /**
   * 复选框改变时，复选框组集合
   * @param {*} e 
   */
  HandelItemChange(e) {
    console.log(e,"===");
    this.setData({
      ids: e.detail.value
    });
  },
  /**
   * 点击确认支付事件处理
   */
  payClick() {
    console.log(this.data.order, "确认支付");
    // 1.生成订单插入数据库
    // 2.删除购物车数据库
    // 3.删除小程序页面数据
    wx.showToast({
      title: '支付成功',
      icon: 'success',
      duration: 1000
    })
  },
  /**
   * 点击结算按钮
   */
  settleBtn() {
    let checkedList = this.data.listData.filter((item) => {
      if(this.data.ids.includes(item._id)) {
        return true;
      }
      return false;
    });
    console.log("结算产品", this.data.ids, checkedList);
    let order = [];
    let amount = 0;
    for(let item of checkedList) {
      amount = amount + item.num * Number(item.sellPrice);
      order.push(item);
    }
    this.setData({
      show: true,
      settleAmount: amount,
      order: order
    });
    let orderStr = JSON.stringify(order);
    let url = "../order/confirm/confirmOrder?orderInfo="+ orderStr+"&totalAmount="+amount
    wx.navigateTo({
      url: url,
    })
  },
  /**
   * 删除按钮
   */
  delete() {
    const ids = this.data.ids;
    wx.cloud.callFunction({
      // 需调用的云函数名
      name: 'buycarApi',
      // 传给云函数的参数
      data: {
        method: "deleteCar",
        args: ids
      },
      // 成功回调
      complete: (res)=>{
        console.log(res, "删除购物车");
        const temp = this.data.listData.filter((item)=>{
          if(this.data.ids.includes(item._id)) {
            return false;
          }
          return true;
        });
        this.setData({
          listData: temp
        });
        this.setBuycatNum();
      }
    });
  },
  setBuycatNum() {
    wx.cloud.callFunction({
      // 需调用的云函数名
      name: 'buycarApi',
      // 传给云函数的参数
      data: {
        method: "countNum",
        args: {}
      },
      // 成功回调
      complete: (res)=>{
        console.log(res, "购物车总数")
        app.globalData.buyCarNum = res.result.rstData.total;
        wx.setTabBarBadge({
          index: 2,  //tabBar序号，从0开始计数
          text: res.result.rstData.total.toString()
        });
      }
    })
  },
  /**
   * 选择商品属性modal 
   */
  numChange(e) {
    console.log("子组件传值过来了", e.detail)
    let tempList = this.data.listData.map(item => {
      if(item._id ===e.detail.expand._id) {
        item.num = e.detail.count;
      }
      return item;
    })
    this.setData({
      listData: tempList
    });
  },
  changeRedio(e) {
    console.log("子组件传值过来了2", e.detail)
    let tempList = this.data.listData.map(item => {
      if(item._id === this.data.product._id) {
        item.attrName = e.detail.value;
        return item;
      }
      return item;
    })
    this.setData({
      listData: tempList
    });
    this.setData({
      selectAttrIndex: e.detail.index
    });
  },
  close: function () {
      this.setData({
        showStatus: false
      })
  },
  selectModal: function() {
    this.setData({
      showStatus: true
    })
  },
  /**
   * 打开选择属性的modal
   * @param {*} e 
   */
  attrBtn: function(e) {
    let product = e.currentTarget.dataset.product;
    console.log(e,"修改属性", product);
    let index = 0;
    for(let i=0; i<product.attr.length; i++) {
      if(product.attr[i].attrName === product.attrName) {
        index = i;
        break;
      }
    }
    let temp = e.currentTarget.dataset.product.attr.map(item =>{
      return {
        label: item.attrName,
        value: item.attrName
      }
    });
    this.setData({
      product: e.currentTarget.dataset.product,
      options: temp,
      selectAttrIndex: index
    });
    console.log("选项", temp);
    this.selectModal();
  }
})